<?php
namespace app\home\controller;
use think\facade\Config;
use think\facade\Env;
use think\Request;

class Error extends Base
{
    public function initialize()
    {
        $conf = \app\backend\model\Config::column('value','key');
        Config::set("system", $conf);
        Config::set("theme", \app\common\model\Theme::where('status', 1)->find());

        define("TEMPLATE_PATH", Env::get('root_path'). "template/" . Config::get('theme')['path'] . '/' );

        parent::initialize();
    }
//
//    protected function initialize()
//    {
//        echo 'init<br/>';
//    }

    public function index(Request $request)
    {
        return $this->fetchTemplate($request);
    }
    public function _empty(Request $request)
    {
        return $this->fetchTemplate($request);
    }

    /*
     * 路径如：/news/newslist/5_6_t_6.html
     * 模板路径：template/news/newslist.html 模板文件必须有两层
     * 参数为：5_6_t，模板中可以通过{$params[2]}得到6, 如果没有参数的, 参数默认会赋值为0
     * */
    private function fetchTemplate($request)
    {

        $url = $request->url();

        if($sp = strpos($url,"?")) {
            $url = substr($url, 0, $sp);
        }

        $url = str_replace(['.html','.htm'],"", $url);
        $url_arr = explode('/', $url);

        if (count($url_arr) < 1) {
            $this->error("路径错误");
        }
        if (!isset($url_arr[1]) || $url_arr[1] == '') {
            $url_arr[1] = 'index';
        }
        if (!isset($url_arr[2]) || $url_arr[2] == '') {
            $url_arr[2] = 'index';
        }
        if (isset($url_arr[3])) {
//            if($sp = strpos($url_arr[3],"?")) {
//                $pp = substr($url_arr[3],0,$sp);
//            } else{
//                $pp = $url_arr[3];
//            }
            $params = explode('_', $url_arr[3]);

        } else {
            $params = 0; // 路径里第三个默认参数是0
        }
        if(request()->isPost()) {
            return action('Handler/handlePost',['act' => input('get.act')]);
        }

        return $this->template($url_arr[1] . '/'. $url_arr[2], [
            '_params' => $params,
            '_asset' => 'abc',
            '_test' => time(),
        ]);
    }
}
